package event

import (
	log "github.com/sirupsen/logrus"
	"sync"
)

// 单例创建eventbus
var (
	instance *EventBus
	once     sync.Once
)

// EventHandler 是事件处理函数的类型
type EventHandler func(subscribeId string, data interface{})

// EventSubscription 代表一个事件及其相关的订阅者
type EventSubscription struct {
	Handler     EventHandler
	Subscribers map[string]struct{} // 使用 map 实现唯一订阅者集合
}

// EventBus 是事件总线的结构体
type EventBus struct {
	subscriptions map[EventType]*EventSubscription
	mu            sync.RWMutex
}

// GetEventBus 创建一个单例的事件总线
func GetEventBus() *EventBus {
	once.Do(func() {
		instance = &EventBus{
			subscriptions: make(map[EventType]*EventSubscription),
		}
	})
	return instance
}

// Subscribe 注册订阅者，确保每个订阅者ID是唯一的
func (eb *EventBus) Subscribe(event EventType, subscriberID string) {
	eb.mu.Lock()
	defer eb.mu.Unlock()

	if subscription, exists := eb.subscriptions[event]; exists {
		// 如果事件已经存在，则添加唯一订阅者
		subscription.Subscribers[subscriberID] = struct{}{}
	} else {
		// 如果事件不存在，打印日志
		log.Printf("Event type '%s' not found for subscriber '%s'. Please register the handler first.", event, subscriberID)
	}
}

// Unsubscribe 取消指定事件的订阅者
func (eb *EventBus) Unsubscribe(event EventType, subscriberID string) {
	eb.mu.Lock()
	defer eb.mu.Unlock()

	if subscription, exists := eb.subscriptions[event]; exists {
		// 从订阅者集合中删除指定的订阅者
		if _, subscribed := subscription.Subscribers[subscriberID]; subscribed {
			delete(subscription.Subscribers, subscriberID)
			log.Printf("Subscriber '%s' unsubscribed from event '%s'.", subscriberID, event)
		} else {
			log.Printf("Subscriber '%s' not found in event '%s' subscriptions.", subscriberID, event)
		}
	} else {
		log.Printf("Event type '%s' not found.", event)
	}
}

// RegisterHandler 注册事件处理函数
func (eb *EventBus) RegisterHandler(event EventType, handler EventHandler) {
	eb.mu.Lock()
	defer eb.mu.Unlock()

	// 创建或更新事件订阅
	eb.subscriptions[event] = &EventSubscription{
		Handler:     handler,
		Subscribers: make(map[string]struct{}),
	}
}

// Publish 发布事件并调用处理函数，通知所有订阅者
func (eb *EventBus) Publish(event EventType, data interface{}) {
	eb.mu.RLock()
	defer eb.mu.RUnlock()

	if subscription, exists := eb.subscriptions[event]; exists && subscription.Handler != nil {
		// 遍历所有订阅者并通知
		for subscriberID := range subscription.Subscribers {
			subscription.Handler(subscriberID, data)
		}
	} else if !exists {
		// 如果事件类型未找到，打印日志
		log.Warningf("No handler found for event type '%s'.", event)
	}
}
